<?php

namespace App\Kuafu\Banner\Model;

use App\Kuafu\Banner\Exceptions\BannerException;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\User\Service\AuthService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Banner\Enum\BannerCodeEnum;

class BannerConfigModel extends BaseModel
{
    use KfSoftDeletes;

    protected $connection = 'mysql';
    protected $table      = 'banner_config';
    protected $primaryKey = 'id';
    protected $fillable   = ['name', 'desc', 'updatedByUid', 'createdByUid'];

    protected $hidden = [
        'updatedAt',
        'isDeleted'
    ];

    public static function getDataPage(int $pageSize, int $pageNum)
    {
        return self::query()
                   ->orderByDesc('id')
                   ->paginate($pageSize, ['id', 'name', 'desc'], 'page', $pageNum);
    }

    public static function getDataById(int $id)
    {
        return self::query()->where('id', $id)->first();
    }

    /**
     * 横幅添加
     *
     * @param array $data
     * @return Builder|Model
     */
    public static function addData(array $data)
    {
        return self::query()->create($data);
    }

    /**
     * 横幅修改
     * @param int $id
     * @param array $data
     * @return int
     * @throws BannerException
     */
    public static function setData(int $id, array $data): int
    {
        $bannerName = BannerModel::query()->where('name', $data['name'])->get()->toArray();
        if ($bannerName) {
            throw new BannerException(BannerCodeEnum::ERR_BANNER_NAME_EXIST);
        }
        return BannerConfigModel::where('id', $id)->update($data);
    }

    /**
     * @param int $id
     * @return int
     * 横幅删除【删除前判断横幅下面是否有广告，如果有，则不允许删除】
     * @throws BannerException|\App\Kuafu\User\Exceptions\UserException
     */
    public static function delData(int $id): int
    {
        $bannerConfig = BannerModel::query()->where('configId', $id)->get()->toArray();

        if (!empty($bannerConfig)) {
            throw new BannerException(BannerCodeEnum::ERR_BANNER_CONFIG_HAVE_DATA);
        }

        return self::query()->where('id', $id)->update(['isDeleted' => 1, 'updatedByUid' => AuthService::getUserId()]);
    }

}
